import React, { ElementRef, memo, useEffect, useRef, useState } from 'react'
import type { FC, ReactNode } from 'react'
import { Carousel } from 'antd'

import { shallowEqualApp, useAppDispatch, useAppSelector } from '@/store'
import { fetchDiscoverTopBanner } from '@/store/modules/discover'
import { TopBannerWrapper } from './style'
import { useNavigate } from 'react-router-dom'

interface IProps {
  children?: ReactNode
}

const Banner: FC<IProps> = () => {
  const dispatch = useAppDispatch()

  useEffect(() => {
    // 获取轮播图数据
    dispatch(fetchDiscoverTopBanner())
  }, [])

  // 从store中获得数据
  const { topBanner } = useAppSelector(
    (state) => ({
      topBanner: state.discover.topBanner
    }),
    shallowEqualApp
  )

  const navigate = useNavigate()
  // 跳转到歌曲详情页
  const toSongDetail = (item: any) => {
    navigate(`/discover/songDetail?id=${item.targetId}`)
  }

  // 渲染轮播图
  const renderBanner = () => {
    return topBanner.map((item: any) => {
      return (
        <div
          key={item.imageUrl}
          onClick={() => toSongDetail(item)}
          className="carousel_item"
        >
          <img className="image" src={item.imageUrl} />
        </div>
      )
    })
  }

  // 当前激活轮播图的索引
  const [indexActive, setIndexActive] = useState(0)
  // 轮播图ref
  const bannerRef = useRef<ElementRef<typeof Carousel>>(null)

  // 轮播图切换
  const beforChange = (from: number, to: number) => {
    setIndexActive(to)
  }

  // 轮播图的背景
  const imageUrl = topBanner[indexActive]?.imageUrl + '?imageView&blur=40x20'

  // 上一张轮播图
  const prevChange = () => {
    bannerRef.current?.prev()
  }

  // 下一张轮播图
  const nextChange = () => {
    bannerRef.current?.next()
  }

  return (
    <TopBannerWrapper
      style={{
        background: `url(${imageUrl}) center center / 6000px`
      }}
    >
      <div className="content">
        <div className="banner">
          <Carousel
            autoplay
            dots={false}
            infinite={true}
            ref={bannerRef}
            fade={true}
            beforeChange={beforChange}
            className="carousel"
          >
            {renderBanner()}
          </Carousel>
        </div>
        <div className="download"></div>
        <button className="btn left" onClick={prevChange}></button>
        <button className="btn right" onClick={nextChange}></button>
      </div>
    </TopBannerWrapper>
  )
}

export default memo(Banner)
